<?php
	if (!isset($_SESSION)) {
		 session_start();
	}
	// Clear previous messages.
	if(isset($_SESSION['error'])) unset($_SESSION['error']);
	if(isset($_SESSION['success'])) unset($_SESSION['success']);
	
	// Get values from the form
	$batchDate = $_POST['batchDate'];
	$batchDescription = $_POST['batchDescription'];
	
	// Give date format for the date
	$dateFormat = '/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/';
	
	// Check for validation
	if($batchDate == ""){
		$_SESSION['error'] = "Pleace complete the mandatory fields";
		$_SESSION['page'] = "addBatches.php";
	}else{
		if(preg_match($dateFormat, $batchDate)==true){
			include("../dbconnection.php");
			if($res = mysql_query("SELECT batchDate FROM batches ORDER BY batchId DESC LIMIT 1")){
				while($row = mysql_fetch_array($res)){
					$prevBatchDate = $row['batchDate'];
					echo $prevBatchDate;
				}
				if($prevBatchDate < $batchDate){
					mysql_query("INSERT INTO batches (batchDate, batchDescription) 
							VALUES ('".$batchDate."', '".$batchDescription."')");
					$_SESSION['success'] = "batch is inserted successfully";
					$_SESSION['page'] = "addStock.php";
				}else{
					$_SESSION['error'] = "New batch date should be greater than previous batch date";
					$_SESSION['page'] = "addBatches.php";
				}
			}else{
				$_SESSION['error'] = "Error occured";
				$_SESSION['page'] = "addBatches.php";
			}
		}else{
			$_SESSION['error'] = "Pleace enter the correct date format";
			$_SESSION['page'] = "addBatches.php";
		}
	}
	header('Location: ../../');	
?>	